<meta charset="UTF-8">
<div id="importsim">
    <input type="file" id="file" style="display: none;" />
    <div class="full" style="padding: 10px;">
        <h3 class="h3-title">{{$t('bgMgr.importSimInfo')}}</h3>
        <div style="padding: 10px 0;">
            <i-table border ref="table" :columns="columns" :loading="loading" :data="tableData" :height="taleHeight"></i-table>
        </div>
        <div style="padding: 5px; text-align: center;border: 1px solid #DCDEE2;">
            <i-button @click="importTownerInfo">{{$t('insure.importFile')}}</i-button>
            <i-button @click="handleSubmit" :loading="loading" style="margin: 0 10px;">{{$t('header.submit')}}</i-button>
            <i-button @click="downloadTemplate">{{$t('insure.templateDownload')}}</i-button>
        </div>
    </div>
    <script>
        vueInstanse = new Vue({
            el: "#importsim",
            i18n: utils.getI18n(),
            data: {
                taleHeight: 300,
                loading: false,
                columns: [{
                    type: 'index',
                    width: 60
                }, {
                    title: isZh ? '手机号码' : 'SIM Phone No.',
                    key: "phonenum",
                    width: 140,
                }, {
                    title: 'ICCID',
                    key: "iccid"
                }, {
                    title: 'IMSI',
                    key: "imsi"
                }, {
                    title: vRoot.$t('insure.cardMerchants'),
                    key: "provider",
                    width: 100,
                }, {
                    title: vRoot.$t('insure.flowPackage'),
                    key: "flowpackage",
                    width: 120,
                }, {
                    title: vRoot.$t('insure.activationTime'),
                    key: "starttime",
                    width: 120,
                }, {
                    title: vRoot.$t('insure.dueDate'),
                    key: "endtime",
                    width: 120,
                }, {
                    'title': vRoot.$t('insure.addStatus'),
                    width: 120,
                    render: function(h, params) {
                        var status = params.row.status;
                        var statusStr = '';
                        var color = '';
                        switch (status) {
                            case -1:
                                statusStr = vRoot.$t('insure.notSubmitted');
                                color = '#000';
                                break;
                            case 0:
                                statusStr = params.row.cause;
                                color = '#e4393c';
                                break;
                            case 1:
                                statusStr = vRoot.$t('insure.submitSucc');
                                color = '#007ACC';
                                break;
                        }
                        return h('span', {
                            style: {
                                color: color
                            }
                        }, statusStr)
                    },
                }, {
                    'title': vRoot.$t('alarm.action'),
                    width: 85,
                    render: function(h, params) {
                        return h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.tableData.splice(params.index, 1);
                                    }
                                }
                            },
                            vRoot.$t('insure.remove'))
                    }
                }],

                tableData: [],

                excelX: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
            },
            methods: {
                calcTableHeight: function() {
                    var wHeight = window.innerHeight;
                    if (wHeight < 760) {
                        wHeight = 760;
                    }
                    this.taleHeight = wHeight - 170;
                },
                downloadTemplate: function() {
                    var a = document.createElement('a');
                    a.href = myUrls.apihost + (isZh ? 'simtemplate.xlsx' : 'simtemplate_en.xlsx');
                    a.download = 'simtemplate.xlsx';
                    a.click();
                },
                handleSubmit: function() {
                    if (this.tableData.length == 0) {
                        this.$Message.error(vRoot.$t('insure.importOwnerNameTips'));
                        return;
                    }
                    this.loading = true;
                    var tableData = deepClone(this.tableData),
                        me = this;
                    var url = myUrls.importSimInfo();
                    var data = {
                        siminfos: tableData,
                        isforcecover: true,
                    }
                    utils.sendAjax(url, data, function(respData) {
                        me.loading = false;
                        if (respData.status == 0) {
                            if (respData.total === respData.success) {
                                me.$Message.success(vRoot.$t('insure.importSucceeded'));
                                me.tableData.forEach(function(item) {
                                    item.status = 1;
                                });
                            } else {
                                me.$Message.error(vRoot.$t('insure.total') + ":" + respData.total + "," + vRoot.$t('insure.fail') + ":" + respData.fail);
                                var errorrecords = respData.errorrecords;
                                var tableData = me.tableData;
                                errorrecords.forEach(function(failItem) {
                                    tableData.forEach(function(item) {
                                        if (failItem.deviceid == item.deviceid) {
                                            item.status = 0;
                                            item.cause = failItem.cause;
                                        }
                                    });
                                });
                                tableData.forEach(function(item) {
                                    if (item.status == -1) {
                                        item.status = 1;
                                    }
                                });
                                me.tableData = tableData;
                            }
                        } else {
                            me.$Message.error(vRoot.$t('insure.importFailed'));
                        }
                    }, function() {
                        me.loading = false;
                        me.$Message.error(vRoot.$t('insure.importTimeout'));
                    });
                },
                importTownerInfo: function() {
                    this.fileEl.files.length = 0;
                    this.fileEl.value = "";
                    this.fileEl.click();
                },
                readWorkbookFromLocalFile: function(file, callback) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var data = e.target.result;
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        if (callback) callback(workbook);
                    };
                    reader.readAsBinaryString(file);
                },
                parserExcelData: function(excelData) {
                    try {
                        var indexY = 2;
                        var tableData = [];
                        while (true) {
                            var phonenumKey = this.excelX[1] + indexY; //设备ID
                            var iccidKey = this.excelX[2] + indexY; //防盗号
                            var imsiKey = this.excelX[3] + indexY; // 车架号
                            var providerKey = this.excelX[4] + indexY; //保险公司
                            var flowpackageKey = this.excelX[5] + indexY; //保单号
                            var starttimeKey = this.excelX[6] + indexY; //投保日期
                            var endtimeKey = this.excelX[7] + indexY; //生效日期


                            if (excelData[phonenumKey] == undefined) {
                                break;
                            }

                            tableData.push({
                                phonenum: excelData[phonenumKey].v,
                                iccid: excelData[iccidKey] ? excelData[iccidKey].v : '',
                                imsi: excelData[imsiKey] ? excelData[imsiKey].v : '',
                                provider: excelData[providerKey] ? excelData[providerKey].v : "",
                                flowpackage: excelData[flowpackageKey] ? excelData[flowpackageKey].v : "",
                                starttime: excelData[starttimeKey] ? excelData[starttimeKey].v : "",
                                endtime: excelData[endtimeKey] ? excelData[endtimeKey].v : "",
                                status: -1
                            })

                            indexY++;
                        }
                        this.tableData = tableData;
                    } catch (error) {
                        this.$Message.error(vRoot.$t('insure.importExcelFailTips'));
                    }

                }
            },
            mounted: function() {
                var me = this;
                this.fileEl = document.getElementById('file');
                this.fileEl.onchange = function(e) {
                    var idx = e.srcElement.value.lastIndexOf('.');
                    var houzhui = e.srcElement.value.slice(idx);
                    if (houzhui.indexOf('xlsx') == -1) {
                        me.$Message.error(vRoot.$t('insure.importExcelTips'));
                        return;
                    }
                    var file = e.target.files[0]
                    me.readWorkbookFromLocalFile(file, function(workbook) {
                        me.parserExcelData(workbook.Sheets[isZh ? '手机卡信息' : 'siminfo'])
                    });
                };
                this.calcTableHeight();
                window.onresize = function() {
                    me.calcTableHeight();
                }
            },
        })
    </script>
</div>